package com.define.ssh.action.userconfig;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.define.ssh.action.admin.BaseAdminAction;
import com.define.ssh.model.Compdept;
import com.define.ssh.model.Deptuser;
import com.define.ssh.model.FictitiousTeam;
import com.define.ssh.model.FictitiousUser;
import com.define.ssh.model.UserInfo;
import com.define.ssh.service.CompdeptService;
import com.define.ssh.service.DeptuserService;
import com.define.ssh.service.FictitiousTeamService;
import com.define.ssh.service.FictitiousUserService;
import com.define.ssh.service.GroupinfoRegularService;
import com.define.ssh.service.UserInfoService;
import com.define.ssh.util.InterfaceIpData;
import com.define.ssh.util.SystemUtil;

/**
 * 
 * @author wwc
 * 
 */
@ParentPackage("userconfig")
public class VirtualGroupAction extends BaseAdminAction {

	/** 页面传递参数过来 */
	protected int pageSize;
	protected int pageNum;

	@Resource(name = "userInfoServiceImpl")
	private UserInfoService userInfoService;

	@Resource(name = "fictitiousTeamServiceImpl")
	private FictitiousTeamService fictitiousTeamService;

	@Resource(name = "fictitiousUserServiceImpl")
	private FictitiousUserService fictitiousUserService;

	@Resource(name = "compdeptServiceImpl")
	private CompdeptService compdeptService;

	@Resource(name = "deptuserServiceImpl")
	private DeptuserService deptuserService;

	
	private List<FictitiousTeam> fteamList;
	private FictitiousTeam fteam;
	private FictitiousUser fuser;
	private long fteamid;
	private String data;
	
	public String index() {
		DetachedCriteria dc=DetachedCriteria.forClass(FictitiousTeam.class);
		Object[] type={1,2};
		dc.add(Restrictions.in("updateType", type));
		
		final UserInfo userInfo = (UserInfo) ServletActionContext.getRequest().getSession().getAttribute(
				SystemUtil.USERINFO);
		if(userInfo.getRole().getId()!=1){
			dc.add(Restrictions.eq("userId", userInfo.getId()));
		}
		fteamList = fictitiousTeamService.findByCriteria(dc);
		if (fteamid > 0) {
			fteam = this.fictitiousTeamService.get(fteamid);
		} else {
			if (fteamList.size() > 0) {
				fteam = fteamList.get(0);
			}
		}
		if (fteam != null) {
			final HashMap<String, Object> searchMap = new HashMap<String, Object>();
			pager.setSearchMap(searchMap);
			pager = fictitiousUserService.findPager(pager,Restrictions.in("updateType", type),Restrictions.eq("fid", fteam.getId()));
		}
		return "virtualGroup";
	}

	public String newVirtualGroup() {

		return "newVirtualGroup";
	}

	public String get() {
		
		final FictitiousTeam team = this.fictitiousTeamService.get(fteam
				.getId());
		return ajax(team);
	}

	public String save() {
		fteam.setUpdateType(1);//新增
		fteam.setUpdateTime(new Date());
		final UserInfo userInfo = (UserInfo) ServletActionContext.getRequest().getSession().getAttribute(
				SystemUtil.USERINFO);
		fteam.setUserId(userInfo.getId());
		fteamid = this.fictitiousTeamService.save(fteam);
		/*
		final List<Deptuser> du_list = deptuserService.getAllList();
		for (String userStr : users.split(",")) {
			if (!userStr.equals("")) {
				userStr = userStr.replace("u", "");
				final long userid = Long.parseLong(userStr);
				final FictitiousUser fu = new FictitiousUser();
				fu.setFid(fteamid);
				fu.setUserid(userid);
				final UserInfo ui = this.userInfoService.get(userid);
				fu.setUsername(ui.getName());
				for (final Deptuser du : du_list) {
					if (du.getUserid()
							.equals(Integer.parseInt(ui.getId() + ""))) {
						fu.setDeptname(compdeptService.get(du.getDeptid())
								.getDeptname());
						break;
					}
				}
				this.fictitiousUserService.save(fu);
			}
		}
		*/
		return this.index();
	}

	public String select(){
		fteam = this.fictitiousTeamService.get(fteamid);
		pager=deptuserService.findPagerByFictitiousTeamId(fteamid,pager);
		return "selectVirtualGroup";
	}
	
	public String addUser() {
		for (String userStr : data.split(",")) {
			if (!userStr.equals("")) {
				String[] temp=userStr.split("_");
				long userid=Long.parseLong(temp[1]);
				int deptid=Integer.valueOf(temp[0]);
				DetachedCriteria dc=DetachedCriteria.forClass(FictitiousUser.class);
				dc.add(Restrictions.eq("fid", fteam.getId()));
				dc.add(Restrictions.eq("userid", userid));
				List<FictitiousUser> list=this.fictitiousUserService.findByCriteria(dc);
				if(list.size()>0){
					final FictitiousUser fu = list.get(0);
					fu.setUpdateTime(new Date());
					fu.setUpdateType(1);
					this.fictitiousUserService.update(fu);
				}else{
					final FictitiousUser fu = new FictitiousUser();
					fu.setFid(fteam.getId());
					fu.setUserid(userid);
					UserInfo ui=userInfoService.get(userid);
					Compdept dept=compdeptService.get(deptid);
					fu.setUsername(ui.getName());
					fu.setDeptname(dept.getDeptname());
					fu.setUpdateTime(new Date());
					fu.setUpdateType(1);
					this.fictitiousUserService.save(fu);
				}
			} 
		}
		return ajax(Status.success, "添加成功");
	}
	
	public String delUser() {
		for (String userStr : data.split(",")) {
			if (!userStr.equals("")) {
				FictitiousUser fu=fictitiousUserService.get(Long.valueOf(userStr));
				fu.setUpdateTime(new Date());
				fu.setUpdateType(3);
				this.fictitiousUserService.update(fu);;
			} 
		}
		return ajax(Status.success, "移除成功");
	}

	public String delete() {
		final FictitiousTeam team = this.fictitiousTeamService.get(fteam
				.getId());
		team.setUpdateType(3);//修改
		team.setUpdateTime(new Date());
		this.fictitiousTeamService.update(team);
		return ajax(Status.success, "删除成功");
	}

	public String remove() {
		//
		FictitiousUser fu=fictitiousUserService.get(fuser.getId());
		fu.setUpdateTime(new Date());
		fu.setUpdateType(3);
		this.fictitiousUserService.update(fu);;
		return ajax(Status.success, "移除成功");
	}

	public String update() {
		final FictitiousTeam team = this.fictitiousTeamService.get(fteam
				.getId());
		team.setUpdateType(2);//修改
		team.setName(fteam.getName());
		team.setRemark(fteam.getRemark());
		team.setUpdateTime(new Date());
		this.fictitiousTeamService.update(team);
		return ajax(Status.success, "修改成功");
	}

	
	/**
	 * 取部门树数据
	 * 
	 * @return
	 */
	public String getUserIds() {
		final DetachedCriteria dc = DetachedCriteria
				.forClass(FictitiousUser.class);
		dc.add(Restrictions.eq("fid", fteam.getId()));
		final List<FictitiousUser> list = this.fictitiousUserService
				.findByCriteria(dc);

		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final FictitiousUser fu = list.get(i);
			sb.append("{");
			sb.append("id:\"u" + fu.getUserid() + "\"");
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	/**
	 * 取部门树数据
	 * @return
	 */
	public String getDeptUserTree(){
		 DetachedCriteria dt = DetachedCriteria.forClass(Compdept.class);
		 dt.add(Restrictions.eq("company.id",InterfaceIpData.compid));
		 dt.add(Restrictions.eq("pid",0));
		 List<Compdept> list = this.compdeptService.findByCriteria(dt);
		 StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final Compdept dept = list.get(i);
			sb.append("{");
			sb.append("id:" + dept.getId());
			sb.append(",pId:" + dept.getPid());
			sb.append(",name:\"" + dept.getDeptname() + "\"");
			 DetachedCriteria dt1 = DetachedCriteria.forClass(Compdept.class);
			 dt1.add(Restrictions.eq("pid",dept.getId()));
			 List<Compdept> list1 = this.compdeptService.findByCriteria(dt1);
			if(list1!=null&&list1.size()>0){
				sb.append(",open:true");
				sb.append(",isParent:true");
			}
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	
	
	/**
	 * 取部门树数据
	 * 
	 * @return
	 */
	public String getUserTT() {
		
		try {
			String deptid = super.getRequest().getParameter("id");
			DetachedCriteria dt1 = DetachedCriteria.forClass(Compdept.class);
			dt1.add(Restrictions.in("updatetype", new Object[]{1,2}));
			dt1.add(Restrictions.eq("company.id",InterfaceIpData.compid));
			dt1.add(Restrictions.eq("pid",Integer.valueOf(deptid)));
			List<Compdept> list = this.compdeptService.findByCriteria(dt1);
			//DetachedCriteria dt = DetachedCriteria.forClass(Deptuser.class);
			//dt.add(Restrictions.eq("deptid",Integer.valueOf(deptid)));
			//List<Deptuser> du_list = this.compdeptService.findByCriteria(dt);
			 
			StringBuffer sb=new StringBuffer();
			sb.append("[");
			for(int i=0;i<list.size();i++){
				Compdept dept=list.get(i);
				sb.append("{");
				sb.append("id:"+dept.getId());
				sb.append(",pId:"+dept.getPid());
				sb.append(",name:\""+dept.getDeptname()+"\"");
				Integer count=compdeptService.count(dept.getId());
				if(count>0){
					sb.append(",open:true");
					sb.append(",isParent:true");
				}
				sb.append("}");
				if(list.size()>0){
					sb.append(",");
				}
			}
			/*
			for(int i=0;i<du_list.size();i++){
				Deptuser du=du_list.get(i);
				sb.append("{");
				sb.append("id: \""+du.getDeptid()+"_"+du.getUserid()+"\"");
				sb.append(",pId:"+du.getDeptid());
				sb.append(",name:\""+du.getUserInfo().getName()+"\"");
				sb.append(",icon:\"../resources/admin/css/bgimg/u88.png\"");
				
				DetachedCriteria dc=DetachedCriteria.forClass(FictitiousUser.class);
				dc.add(Restrictions.eq("fid", fteam.getId()));
				dc.add(Restrictions.eq("userid", Long.valueOf(du.getUserid()+"")));
				List<FictitiousUser> fu_list=this.fictitiousUserService.findByCriteria(dc);
				if(fu_list.size()>0){
					sb.append(",checked : true");
				}	
				sb.append("}");
				if(i!=du_list.size()){
					sb.append(",");
				}
			}
			*/
			sb.append("]");
			return ajax(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getUserListByDept() {
		try {
			DetachedCriteria dc = DetachedCriteria.forClass(FictitiousUser.class);
			dc.add(Restrictions.eq("fid",fteam.getId()));
			dc.add(Restrictions.in("updateType", new Object[]{1,2}));
			List<FictitiousUser> fu_list = this.fictitiousUserService.findByCriteria(dc);
			
			
			String deptidStr = super.getRequest().getParameter("id");
			Integer deptid=null;
			if(StringUtils.isNotEmpty(deptidStr)){
				deptid=Integer.valueOf(deptidStr);
			}
			pager=this.deptuserService.find(pager, deptid, data);
			
			List<Deptuser> du_list = (List<Deptuser>) pager.getResult();
			StringBuffer sb=new StringBuffer();
			
			sb.append(",\"list\":[");
			for(Deptuser du:du_list){
				//if(du.getUserInfo().getUpdatetype()!=3&&this.getFictitiousUser(du.getUserInfo().getId(), fu_list)==null){
				if(1==1){
					if(sb.length()>10){
						sb.append(",");
					}
					sb.append("{");
					sb.append("\"id\":\""+du.getUserInfo().getId()+"\"");
					sb.append(",\"name\":\""+du.getUserInfo().getName()+"\"");
					sb.append(",\"deptName\":\""+du.getDept().getDeptname()+"\"");
					sb.append(",\"local\":\""+du.getUserInfo().getLocal()+"\"");
					sb.append("}");
				}
			}
			sb.append("]");
			
			StringBuffer sb1=new StringBuffer();
			sb1.append("{");
			sb1.append("\"pageCount\":\""+pager.getPageCount()+"\"");
			sb1.append(",\"pageNumber\":\""+pager.getPageNumber()+"\"");
			sb1.append(sb);
			sb1.append("}");
			return ajax(sb1.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private FictitiousUser getFictitiousUser(long userid,List<FictitiousUser> fu_list){
		for(FictitiousUser fu:fu_list){
			if(fu.getUserid()==userid){
				return fu;
			}
		}
		return null;
	}
	
	private Long getFictitiousUser(String[] users, FictitiousUser fu){
		int a=0;
		for(String useridStr:users){
			long userid=Long.valueOf(useridStr);
			if(fu.getUserid()==userid){
				a++;
			}
		}
		if(a==0){
			return fu.getId();
		}
		return null;
	}
	
	public String getAll() {
		try {
			DetachedCriteria dc = DetachedCriteria.forClass(FictitiousUser.class);
			dc.add(Restrictions.eq("fid",fteam.getId()));
			dc.add(Restrictions.in("updateType", new Object[]{1,2}));
			List<FictitiousUser> fu_list = this.fictitiousUserService.findByCriteria(dc);
			StringBuffer sb=new StringBuffer();
			sb.append("[");
			for(FictitiousUser fu:fu_list){
				if(sb.length()>2){
					sb.append(",");
				}
				sb.append("{");
				sb.append("\"id\":\""+fu.getUserid()+"\"");
				sb.append(",\"name\":\""+fu.getUsername()+"\"");
				sb.append(",\"deptName\":\""+fu.getDeptname()+"\"");
				String local=fu.getUserInfo().getLocal()==null?"":fu.getUserInfo().getLocal();
				sb.append(",\"local\":\""+local+"\"");
				sb.append("}");
			}
			sb.append("]");
			return ajax(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	public String saveUser() {
		DetachedCriteria dc = DetachedCriteria.forClass(FictitiousUser.class);
		dc.add(Restrictions.eq("fid",fteam.getId()));
		List<FictitiousUser> fu_list = this.fictitiousUserService.findByCriteria(dc);
		if(StringUtils.isNotEmpty(data)){
			String[] users=data.split(",");
			for(String useridStr:users){
				long userid=Long.valueOf(useridStr);
				FictitiousUser fu=this.getFictitiousUser(userid, fu_list);
				if(fu==null){
					final FictitiousUser temp = new FictitiousUser();
					temp.setFid(fteam.getId());
					temp.setUserid(userid);
					DetachedCriteria duDc = DetachedCriteria.forClass(Deptuser.class);
					duDc.add(Restrictions.eq("userid",Integer.valueOf(userid+"")));
					List<Deptuser> duList=this.deptuserService.findByCriteria(duDc);
					if(duList.size()>0){
						temp.setUsername(duList.get(0).getUserInfo().getName());
						temp.setDeptname(duList.get(0).getDept().getDeptname());
					}
					temp.setUpdateTime(new Date());
					temp.setUpdateType(1);
					this.fictitiousUserService.save(temp);
				}else{
					if(fu.getUpdateType()==3){
						fu.setUpdateTime(new Date());
						fu.setUpdateType(2);
						this.fictitiousUserService.save(fu);
					}
				}
			}
		}
		return ajax(Status.success, "操作成功");
	}
	
	
	public List<FictitiousTeam> getFteamList() {
		return fteamList;
	}

	public void setFteamList(List<FictitiousTeam> fteamList) {
		this.fteamList = fteamList;
	}

	public FictitiousTeam getFteam() {
		return fteam;
	}

	public void setFteam(FictitiousTeam fteam) {
		this.fteam = fteam;
	}

	public long getFteamid() {
		return fteamid;
	}

	public void setFteamid(long fteamid) {
		this.fteamid = fteamid;
	}



	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public FictitiousUser getFuser() {
		return fuser;
	}

	public void setFuser(FictitiousUser fuser) {
		this.fuser = fuser;
	}

}
